import {createStore} from "stamen";
import {ReducerFn, Reducers} from "stamen/dist/typings";
import Taro from "@tarojs/taro";

interface Tree {
  id: number,
  children: Tree[]
}

interface SubjectPo extends Tree {
  id: number
  subjectName: string
  children: SubjectPo[]
}

interface SubjectStoreState {
  all: SubjectPo[],
  current?: SubjectPo
}

interface SubjectReducers<S> extends Reducers<S> {
  setAll: ReducerFn<S>
  setCurrent: ReducerFn<S>
}

function initCurrentSubject() {
  const value = Taro.getStorageSync('currentSubject')
  if (!value) return undefined
  return JSON.parse(value);
}


export default createStore<SubjectStoreState, SubjectReducers<SubjectStoreState>, any>(
  {
    state: {
      all: [], // 全部
      current: initCurrentSubject() // 当前
    },
    reducers: {
      setAll(state, payload) {
        state.all = payload
      },
      setCurrent(state, payload) {
        state.current = payload
        Taro.setStorageSync("currentSubject", JSON.stringify(payload))
      }
    }
  }
)

// 在书中找到一个节点的最顶点
export function findTopOfTree<E extends Tree>(list: E[], p: E): E | undefined {
  return list.find(item => {
    if (item.id === p.id) return true
    if (item.children && item.children.length) {
      return findTopOfTree(item.children, p)
    }
    return false;
  })
}
